/*
 * NotesFileUtils.java
 * 
 * Copyright (c) 2007
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.dcarew.notes;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;

/**
 * Some static utility methods for some common file manipulations.
 * 
 * @author Devon Carew
 */
public class NotesFileUtils
{
	
	/**
	 * Read the entire contents of the given file and return them as a String. The contents of the
	 * file are assumed to be in UTF8 format.
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static String readTextUTF8(File file)
		throws IOException
	{
		InputStreamReader reader = null;
		
		try
		{
			reader = new InputStreamReader(new FileInputStream(file), "UTF-8"); 
			
			StringBuffer 	str = new StringBuffer(1024);
			char[]			buffer = new char[4096];
			
			int				count = reader.read(buffer);
			
			while (count != -1)
			{
				str.append(buffer, 0, count);
				
				count = reader.read(buffer);
			}
			
			return str.toString();
		}
		finally
		{
			safeClose(reader);
		}
	}
	
	/**
	 * Write the contents of the string to the given file in UTF8 format.
	 * 
	 * @param text
	 * @param file
	 * @throws IOException
	 */
	public static void writeTextUTF8(String text, File file)
		throws IOException
	{
		OutputStreamWriter writer = null;
		
		try
		{
			writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
			
			writer.write(text);
		}
		finally
		{
			safeClose(writer);
		}
	}
	
	/**
	 * Close the given Reader; do not propagate any thrown exceptions.
	 * 
	 * @param reader
	 */
	public static void safeClose(Reader reader)
	{
		try
		{
			reader.close();
		}
		catch (IOException e)
		{
			
		}
	}
	
	/**
	 * Close the given Writer; do not propagate any thrown exceptions.
	 * 
	 * @param writer
	 */
	public static void safeClose(Writer writer)
	{
		try
		{
			if (writer != null)
				writer.close();
		}
		catch (IOException e)
		{
			
		}
	}

}
